<template>
  <div class="sql-query-basic">
    <h1>SQL查询界面</h1>
    
    <div class="status-info">
      <p>页面状态: <span class="status-ok">✅ 正常加载</span></p>
      <p>API导入: <span class="status-ok">✅ 正常</span></p>
      <p>组件状态: <span class="status-ok">✅ 正常</span></p>
    </div>

    <!-- 数据库列表加载测试 -->
    <div class="section">
      <h2>数据库实例列表</h2>
      <el-button @click="loadDatabases" :loading="loading" type="primary">
        {{ loading ? '加载中...' : '加载数据库列表' }}
      </el-button>
      
      <div v-if="error" class="error-message">
        <p>错误信息: {{ error }}</p>
      </div>
      
      <div v-if="databases.length > 0" class="database-grid">
        <div 
          v-for="db in databases" 
          :key="db.id" 
          class="database-card"
          :class="{ 
            'available': db.database_name || db.database_type !== 'mysql',
            'needs-config': db.database_type === 'mysql' && !db.database_name 
          }"
          @click="selectDatabase(db)"
        >
          <div class="db-header">
            <h3>{{ db.name }}</h3>
            <span class="db-type">{{ db.database_type.toUpperCase() }}</span>
          </div>
          <div class="db-details">
            <p>主机: {{ db.host }}:{{ db.port }}</p>
            <p v-if="db.database_name">数据库: {{ db.database_name }}</p>
            <p v-else-if="db.database_type === 'mysql'" class="warning">⚠️ 需要配置数据库名称</p>
          </div>
          <div class="db-status">
            <span v-if="selectedDatabase === db.id" class="selected">✅ 已选择</span>
            <span v-else-if="db.database_name || db.database_type !== 'mysql'" class="available">可用</span>
            <span v-else class="unavailable">需要配置</span>
          </div>
        </div>
      </div>
      
      <div v-else-if="!loading" class="empty-message">
        <p>暂无数据库实例，请先加载数据</p>
      </div>
    </div>

    <!-- SQL查询区域 -->
    <div class="section" v-if="selectedDatabase">
      <h2>SQL查询</h2>
      <div class="current-db">
        <p>当前数据库: <strong>{{ getCurrentDatabase()?.name }}</strong></p>
      </div>
      
      <div class="query-area">
        <el-input
          v-model="sqlContent"
          type="textarea"
          placeholder="请输入SQL语句，例如: SHOW TABLES"
          :rows="6"
          class="sql-input"
        />
        
        <div class="query-actions">
          <el-button 
            @click="executeQuery" 
            :loading="executing"
            :disabled="!sqlContent.trim()"
            type="primary"
            size="large"
          >
            {{ executing ? '执行中...' : '执行查询' }}
          </el-button>
          <el-button @click="clearQuery">清空</el-button>
        </div>
      </div>
      
      <!-- 查询结果 -->
      <div v-if="queryResult" class="result-area">
        <h3>查询结果</h3>
        <div class="result-stats">
          <span>执行时间: {{ queryResult.execution_time }}s</span>
          <span>返回行数: {{ queryResult.row_count }}</span>
          <span>SQL类型: {{ queryResult.sql_type }}</span>
        </div>
        
        <div v-if="queryResult.rows && queryResult.rows.length > 0" class="result-table">
          <table>
            <thead>
              <tr>
                <th v-for="(col, index) in queryResult.columns" :key="index">
                  {{ col }}
                </th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(row, index) in queryResult.rows.slice(0, 20)" :key="index">
                <td v-for="(cell, cellIndex) in row" :key="cellIndex">
                  {{ cell }}
                </td>
              </tr>
            </tbody>
          </table>
          <p v-if="queryResult.rows.length > 20" class="more-data">
            显示前20行，共{{ queryResult.rows.length }}行数据
          </p>
        </div>
        
        <div v-else class="no-data">
          <p>查询执行成功，但没有返回数据</p>
        </div>
      </div>
    </div>
    
    <div v-else class="no-selection">
      <p>请先选择一个数据库实例</p>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { sqlAPI } from '@/api/sql'

// 响应式数据
const loading = ref(false)
const executing = ref(false)
const error = ref('')
const databases = ref([])
const selectedDatabase = ref(null)
const sqlContent = ref('SHOW TABLES')
const queryResult = ref(null)

// 获取当前数据库
const getCurrentDatabase = () => {
  return databases.value.find(db => db.id === selectedDatabase.value)
}

// 加载数据库列表
const loadDatabases = async () => {
  loading.value = true
  error.value = ''
  
  try {
    console.log('开始加载数据库列表...')
    const response = await sqlAPI.getDatabaseInstances()
    console.log('API响应:', response)
    
    // 处理不同的响应格式
    let data = []
    if (response) {
      if (response.results) {
        data = response.results
      } else if (Array.isArray(response)) {
        data = response
      } else if (response.data && Array.isArray(response.data)) {
        data = response.data
      }
    }
    
    databases.value = data
    console.log('加载的数据库列表:', databases.value)
    ElMessage.success(`成功加载 ${data.length} 个数据库实例`)
  } catch (err) {
    console.error('加载数据库失败:', err)
    error.value = err.message || '加载失败'
    ElMessage.error(`加载数据库失败: ${err.message}`)
  } finally {
    loading.value = false
  }
}

// 选择数据库
const selectDatabase = (db) => {
  if (db.database_type === 'mysql' && !db.database_name) {
    ElMessage.warning('该数据库实例未配置数据库名称，无法使用')
    return
  }
  
  selectedDatabase.value = db.id
  queryResult.value = null
  ElMessage.success(`已选择数据库: ${db.name}`)
}

// 执行查询
const executeQuery = async () => {
  if (!selectedDatabase.value || !sqlContent.value.trim()) {
    ElMessage.warning('请选择数据库并输入SQL语句')
    return
  }

  executing.value = true
  
  try {
    console.log('执行查询，参数:', {
      database_id: selectedDatabase.value,
      sql_content: sqlContent.value,
      limit: 1000
    })

    const response = await sqlAPI.executeQuery({
      database_id: selectedDatabase.value,
      sql_content: sqlContent.value,
      limit: 1000
    })

    console.log('查询响应:', response)

    if (response && response.result) {
      queryResult.value = response.result
      ElMessage.success(response.message || '查询执行成功')
    } else {
      throw new Error('响应数据格式错误')
    }
  } catch (err) {
    console.error('查询执行失败:', err)
    
    let errorMessage = '查询执行失败'
    if (err.response?.data?.error) {
      errorMessage = err.response.data.error
    } else if (err.error) {
      errorMessage = err.error
    } else if (err.message) {
      errorMessage = err.message
    }
    
    ElMessage.error(errorMessage)
    queryResult.value = null
  } finally {
    executing.value = false
  }
}

// 清空查询
const clearQuery = () => {
  sqlContent.value = ''
  queryResult.value = null
}
</script>

<style scoped>
.sql-query-basic {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.status-info {
  background: #f0f9ff;
  padding: 15px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.status-ok {
  color: #16a34a;
  font-weight: bold;
}

.section {
  margin-bottom: 30px;
  padding: 20px;
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  background: white;
}

.section h2 {
  margin-top: 0;
  color: #1f2937;
}

.database-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
  margin-top: 20px;
}

.database-card {
  border: 2px solid #e5e7eb;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.2s;
}

.database-card:hover {
  border-color: #3b82f6;
  box-shadow: 0 4px 12px rgba(59, 130, 246, 0.15);
}

.database-card.available {
  border-color: #10b981;
  background: #f0fdf4;
}

.database-card.needs-config {
  border-color: #f59e0b;
  background: #fffbeb;
}

.db-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.db-header h3 {
  margin: 0;
  color: #1f2937;
}

.db-type {
  background: #3b82f6;
  color: white;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: bold;
}

.db-details p {
  margin: 4px 0;
  color: #6b7280;
  font-size: 14px;
}

.warning {
  color: #f59e0b !important;
  font-weight: bold;
}

.db-status {
  margin-top: 12px;
  text-align: right;
}

.selected {
  color: #3b82f6;
  font-weight: bold;
}

.available {
  color: #10b981;
}

.unavailable {
  color: #f59e0b;
}

.current-db {
  background: #f3f4f6;
  padding: 12px;
  border-radius: 6px;
  margin-bottom: 16px;
}

.query-area {
  margin-bottom: 20px;
}

.sql-input {
  margin-bottom: 16px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}

.query-actions {
  display: flex;
  gap: 12px;
}

.result-area {
  border-top: 1px solid #e5e7eb;
  padding-top: 20px;
}

.result-stats {
  display: flex;
  gap: 20px;
  margin-bottom: 16px;
  font-size: 14px;
  color: #6b7280;
}

.result-table {
  overflow-x: auto;
}

.result-table table {
  width: 100%;
  border-collapse: collapse;
  border: 1px solid #e5e7eb;
}

.result-table th,
.result-table td {
  padding: 8px 12px;
  text-align: left;
  border: 1px solid #e5e7eb;
}

.result-table th {
  background: #f9fafb;
  font-weight: bold;
  color: #374151;
}

.result-table tr:nth-child(even) {
  background: #f9fafb;
}

.more-data {
  margin-top: 12px;
  color: #6b7280;
  font-style: italic;
}

.error-message {
  background: #fef2f2;
  border: 1px solid #fecaca;
  color: #dc2626;
  padding: 12px;
  border-radius: 6px;
  margin-top: 12px;
}

.empty-message,
.no-selection,
.no-data {
  text-align: center;
  color: #6b7280;
  padding: 40px;
}
</style>
